package com.itheima.cglib;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class CglibProxy {
    public static void main(String[] args) {
        //定义目标对象
        Honda honda = new Honda();
        Honda proxy = (Honda) Enhancer.create(Honda.class, new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                String methodName = method.getName();
                System.out.println(methodName + "执行了");//前置通知
                Object result = null;
                try {
                    result = method.invoke(honda, objects);
                    System.out.println("后置通知");
                }catch (Exception e) {
                    e.printStackTrace();
                    System.out.println("异常通知");
                } finally {
                    System.out.println("最终通知");
                }
                return result;
            }
        });
        proxy.color();
    }
}
